<?php
/**
 * @package Admin
 * @author Henrique Droog <henridroog@gmail.com>
 * @name CategoriaController
 * @since 12/03/2011
 * @version 1.0
 */
class Admin_CategoriaController extends Zend_Controller_Action
{
    protected $_form;
    protected $_categoria;
    protected $_categoriaMapper;

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        $categorias = new Admin_Model_CategoriaMapper();
        $this->view->entries = $categorias->fetchAll();
    }

    private function getForm(){
        $form = new Admin_Form_CategoriaForm();
        $form->setAction('/admin/categoria/add/')
             ->setMethod('post')
             ->setAttrib('id','form');

        return $form;
    }

    public function addAction()
    {
        $this->_form = $this->getForm();
        $request = $this->getRequest();
        if ($this->getRequest()->isPost()) {
            if ($this->_form->isValid($request->getPost())) {
                $categoria = new Admin_Model_Categoria($this->_form->getValues());
                $mapper = new Admin_Model_CategoriaMapper();
                $mapper->save($categoria);
                return $this->_helper->redirector('index');
            } else {
                $this->_form->populate($this->_request->getPost());
            }
        }
        $this->view->form = $this->_form;
        //$this->view->render('add.phtml');
    }

    public function editAction()
    {
        $this->_form = $this->getForm();
        $request = $this->getRequest();
        $id['id'] = $request->getParam('id');
        if ($id!='') {
           $categoria = new Admin_Model_Categoria($id);
           $mapper = new Admin_Model_CategoriaMapper();
           $res = $mapper->find($id, $categoria);
           $dataForm["id"] = $res->id;
           $dataForm["titulo"] = $res->titulo;
           $dataForm["descricao"] = $res->descricao;
           $dataForm["ativo"] = $res->ativo;
           $dataForm["ordem"] = $res->ordem;
           if(count($res)>=1){
               $this->_form->populate($dataForm);
           }
        }
       // die();
        $this->view->form = $this->_form;
    }

    public function deleteAction()
    {
        $request = $this->getRequest();
        $id['id'] = $request->getParam('id');
        if ($id!='') {
            $categoria = new Admin_Model_Categoria($id);
            $mapper = new Admin_Model_CategoriaMapper();
            $res = $mapper->del($categoria);
        }
        return $this->_helper->redirector('index');
    }


}







